package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"kuangstudy-mall/srvs/stocks-srv/proto"
	"sync"
)

var goodsStocksClient proto.GoodsStocksClient

func InitClient() {
	conn, err := grpc.Dial("127.0.0.1:9400", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	goodsStocksClient = proto.NewGoodsStocksClient(conn)
}

func TestSaveGoodsStocks() {
	goodsStocksInfo := proto.GoodsStocksInfo{GoodsId: 2, Num: 100}
	response, err := goodsStocksClient.SetGoodsStocks(context.Background(), &goodsStocksInfo)
	if err != nil {
		panic(err)
	}
	fmt.Println(response)
}

func TestGetGoodsStocks() {
	goodsStocksInfo := proto.GoodsStocksRequest{GoodsId: 2}
	response, err := goodsStocksClient.GetGoodsStocks(context.Background(), &goodsStocksInfo)
	if err != nil {
		panic(err)
	}
	fmt.Println(response)
}

func TestGoodsStocksSell(w *sync.WaitGroup) {
	defer w.Done()
	goodsStocksInfo := proto.GoodsSellListRequest{
		GoodsList: []*proto.GoodsStocksInfo{
			{GoodsId: 1, Num: 1},
			{GoodsId: 2, Num: 1},
		},
	}
	response, err := goodsStocksClient.GoodsStocksSell(context.Background(), &goodsStocksInfo)
	if err != nil {
		panic(err)
	}
	fmt.Println(response)
}

func TestGoodsStocksReback() {
	goodsStocksInfo := proto.GoodsSellListRequest{
		GoodsList: []*proto.GoodsStocksInfo{
			{GoodsId: 1, Num: 1},
			{GoodsId: 2, Num: 1},
		},
	}
	response, err := goodsStocksClient.GoodsStocksReback(context.Background(), &goodsStocksInfo)
	if err != nil {
		panic(err)
	}
	fmt.Println(response)
}

func main() {
	InitClient()
	// 设置库存
	//TestSaveGoodsStocks()
	// 根据商品ID查询库存服务
	//TestGetGoodsStocks()
	// 商品库存服务扣减
	waitGroup := sync.WaitGroup{}
	waitGroup.Add(10)
	for i := 0; i < 10; i++ {
		go TestGoodsStocksSell(&waitGroup)
	}
	waitGroup.Wait()
	// 商品库存服务归还
	//TestGoodsStocksReback()
}
